package wsepForum.ui.swing.innerPanels;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ExecutionException;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.MatteBorder;

import wsepForum.common.elements.User.UserType;
import wsepForum.domain.exceptions.UnAuthorizedException;
import wsepForum.domain.exceptions.WrongPasswordException;
import wsepForum.network.common.GUIAnswer;
import wsepForum.network.common.GUIAnswer.AnswerType;
import wsepForum.network.common.GUIRequest.RequestType;
import wsepForum.persistance.exceptions.WrongUserNameException;
import wsepForum.ui.swing.SetSwitcher.SetType;
import wsepForum.ui.swing.outerPanels.AOuterPanel;
import wsepForum.ui.swing.workers.ForumWorker;

public class LoginPanel extends AInnerPanel {

	/**
	 *
	 */
	private static final long serialVersionUID = -457515980970838454L;

	/**
	 * Create the panel.
	 */
	public LoginPanel(AOuterPanel oPanel) {
		super(oPanel);
		setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
		setLayout(null);
		setBackground(new Color(230, 230, 250));
		setBounds(20, 93, 716, 364);

		JLabel lblLogin = new JLabel("Login");
		lblLogin.setFont(new Font("Cooper Black", Font.PLAIN, 18));
		lblLogin.setHorizontalAlignment(SwingConstants.CENTER);
		lblLogin.setBounds(311, 11, 94, 40);
		add(lblLogin);


		JLabel lblUserName = new JLabel("User Name:");
		lblUserName.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblUserName.setHorizontalAlignment(SwingConstants.RIGHT);
		lblUserName.setBounds(203, 89, 76, 26);
		add(lblUserName);


		JLabel lblPassword = new JLabel("Password:");
		lblPassword.setHorizontalAlignment(SwingConstants.RIGHT);
		lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblPassword.setBounds(213, 126, 66, 26);
		add(lblPassword);


		final JTextField userField = new JTextField();
		userField.setBounds(289, 93, 153, 20);
		add(userField);
		userField.setColumns(10);


		final JTextField passwordField = new JPasswordField();
		passwordField.setColumns(10);
		passwordField.setBounds(289, 130, 153, 20);
		add(passwordField);


		JButton btnLogin = new JButton("Login");
		btnLogin.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnLogin.setBounds(376, 161, 66, 23);
		btnLogin.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				ForumWorker<AInnerPanel> worker = new ForumWorker<AInnerPanel>(outerPanel.getConnection()){
					@Override
					protected AInnerPanel doInBackground() throws Exception {
						String user = userField.getText();
						String password = passwordField.getText();
						AInnerPanel returnedPanel = LoginPanel.this;
						if((!user.isEmpty())&&(!password.isEmpty())){
							if ((user.length()>=4) && (user.length()<=30)) {
								GUIAnswer loginAns = request(RequestType.LOGIN, new Object[] {user,password});
								outerPanel.setNumOfConnected(loginAns.getNumOfConnected());
								if((loginAns.getAnswerType().equals(AnswerType.ANSWER))&&(loginAns.getArguments().length==2)&&((Boolean)loginAns.getArguments()[0])){
									SetType setType = SetType.valueOf(((UserType)loginAns.getArguments()[1]).name());
									outerPanel.changeSet(setType);
								}
								else {
									returnedPanel = handleLoginExceptions((Exception) loginAns.getArguments()[0]);
								}
							}
							else {
								JOptionPane.showMessageDialog(null, "User name have to be 5 to 30 letters. Please try again", "Too short/long user name",JOptionPane.ERROR_MESSAGE);
							}

						}
						return returnedPanel;
					}
					@Override
					public void done(){
						try {
							outerPanel.swapInnerPanel(get());
						} catch (InterruptedException e) {
							outerPanel.swapInnerPanel(handleLoginExceptions(e));
						} catch (ExecutionException e) {
							outerPanel.swapInnerPanel(handleLoginExceptions(e));
						}
					}

					private AInnerPanel handleLoginExceptions(Exception thrown){
						try {
							throw thrown;
						}catch (WrongPasswordException e) {
							JOptionPane.showMessageDialog(null, "the password you entered is wrong. please try again.", "Wrong password",JOptionPane.ERROR_MESSAGE);
							return LoginPanel.this;
						} catch (WrongUserNameException e) {
							JOptionPane.showMessageDialog(null, "no such user " + e.getWrongUsername() ,"Wrong user",JOptionPane.ERROR_MESSAGE);
							return LoginPanel.this;
						} catch (UnAuthorizedException e) {
							JOptionPane.showMessageDialog(null, "You are already logged in", "Can't login",JOptionPane.ERROR_MESSAGE);
							return requestHomePanel(outerPanel);
						} catch (Exception e) {
							JOptionPane.showMessageDialog(null, "operation failed! please try again\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
							return LoginPanel.this;
						}
					}

				};
				worker.execute();
			}
		});
		add(btnLogin);
	}
}
